(function() {
	angular
		.module('ydApp.clinic', [])
		.config(function($stateProvider) {
			$stateProvider.state('add-clinic', {
				cache: false,
				url: '/add-clinic',
				controller: "addClinicCtrl",
				templateUrl: 'views/clinic/add-clinic.html'
			});
			$stateProvider.state('add-clinic-succ', {
				cache: false,
				url: '/add-clinic-succ',
				controller: "addClinicSuccCtrl",
				templateUrl: 'views/clinic/add-clinic-succ.html'
			});
			$stateProvider.state('del-clinic', {
				url: '/del-clinic:id',
				controller: "delClinicCtrl",
				templateUrl: 'views/clinic/del-clinic.html'
			});
		})
		.controller("addClinicCtrl", addClinicCtrl)
		.controller("addClinicSuccCtrl", addClinicSuccCtrl)
		.controller("delClinicCtrl", delClinicCtrl);

	function addClinicCtrl($scope, $state, localStore, xhr, popup, bdCalendar) {
		var vm = $scope.vm = {};

		vm.createmodel = {};

		$scope.$watch('vm.date', function() {
			for (var i = 0; i < vm.list.length; i++) {
				if ((new Date(vm.date).toLocaleDateString()) == (new Date(vm.list[i]).toLocaleDateString())) {
					vm.add = false;
					$state.go('del-clinic', {
						id: vm.model[i].id
					});
					return;
				}
			}
			vm.add = true;
			vm.createmodel.startTimeString = vm.date + ' 00:00:01';
			vm.createmodel.endTimeString = vm.date + ' 23:59:59';
		})

		vm.list = [];

		var user = localStore.get("user");

		vm.createmodel.doctorId = user.id;

		xhr.get("HealthInquiry/com/clinic/findByDoctorId", {
			doctorId: user.id
		}).then(function(result) {
			vm.model = result.data;
			for (var i = 0; i < vm.model.length; i++) {
				vm.list.push(vm.model[i].startTime)
			}
		})

		vm.limit = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

		vm.submit = function() {
			xhr.get("HealthInquiry/com/clinic/saveOrUpdate", vm.createmodel).then(function(result) {
				$state.go('add-clinic-succ');
			})
		};
	}

	function addClinicSuccCtrl($state, $timeout) {
		$timeout(function() {
			$state.go('add-clinic');
		}, 2000)
	}

	function delClinicCtrl($state, $scope, $timeout, xhr, localStore, $stateParams) {
		var vm = $scope.vm = {};

		vm.user = localStore.get("user");

		xhr.get("HealthInquiry/com/clinic/findById", {
			id: $stateParams.id
		}).then(function(result) {
			vm.model = result.data;
		})

		vm.submit = function() {
			xhr.get("HealthInquiry/com/clinic/deleteByDoctorId", {
				id: $stateParams.id,
				doctorId: vm.user.id
			}).then(function(result) {
				$state.go('add-clinic-succ');
			})
		};
	}
})();